package jing.upnp.factory.loader.impl;

import android.content.Context;
import android.util.Log;

import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.Response;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;

import jing.upnp.factory.loader.DocumentLoader;

public class HttpClientOkLoader implements DocumentLoader {

    private static final String TAG = "HttpClientOkLoader";
    private static final Object classLock = HttpClientOkLoader.class;
    private static HttpClientOkLoader instance = null;
    private OkHttpClient client;

    public static HttpClientOkLoader getInstance() {
        synchronized (classLock) {
            if (instance == null) {
                instance = new HttpClientOkLoader();
            }

            return instance;
        }
    }

    private HttpClientOkLoader() {
        client = new OkHttpClient();
    }

    @Override
    public InputStream getStream(Context context, String url) {
        InputStream is = null;

        do {
            Log.e(TAG, String.format("getStream %s", url));

            try {
                Request request = new Request.Builder().url(url).build();
                Response response = client.newCall(request).execute();
                if (! response.isSuccessful()) {
                    Log.e(TAG, "call failed: " + response.code() + " message: " + response.message());
                    break;
                }

                is = new ByteArrayInputStream(response.body().bytes());
            } catch (IllegalArgumentException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        } while (false);

        return is;
    }
}
